package com.xxgc.cloud.auth.springcloudauth.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxgc.cloud.auth.springcloudauth.controller.pojo.UserRolesAndPermissions;
import com.xxgc.cloud.auth.springcloudauth.entity.RolesAndPermissions;
import com.xxgc.cloud.auth.springcloudauth.entity.Users;
import com.xxgc.cloud.auth.springcloudauth.entity.UsersAndRoles;
import com.xxgc.cloud.auth.springcloudauth.mapper.*;
import com.xxgc.cloud.auth.springcloudauth.service.IUsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Mr.Abel
 * @since 2022-11-22
 */
@Slf4j
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Resource
    private UsersAndRolesMapper uarm;

    @Resource
    private RolesAndPermissionsMapper rapm;

    @Resource
    private PermissionsMapper pm;

    @Resource
    private RolesMapper rm;


    /**
     * 注册
     * @param users 用户对象
     * @return 用户对象
     */
    @Override
    public Boolean userRegister(Users users) {
        //生成用户名 后期可修改一次  一年一次
        String userName = "chou-" + IdUtil.simpleUUID().substring(0,8);;
        users.setUserName(userName);
        //给md5添加盐值
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String salt = IdUtil.simpleUUID();
        salt = salt.substring(0,12);
        md5.setSalt(salt.getBytes());
        String digestHex = md5.digestHex(users.getUserPass());

        //在对象里添加
        users.setSalt(salt);
        //加密之后的密码和盐值
        users.setUserPass(digestHex);

        //int insert = baseMapper.insert(users);
        return super.save(users);
    }

    @Override
    public Users selectSaltByPhoneNumber(String phoneNum) {
        QueryWrapper<Users> qw = new QueryWrapper<>();
        qw.eq("phone_number",phoneNum);
        return baseMapper.selectOne(qw);
    }

    @Override
    public Users userLogin(Users users) {
        LambdaQueryWrapper<Users> qw = new LambdaQueryWrapper<>();
        qw.eq(Users::getUserPass,users.getUserPass()).eq(Users::getPhoneNumber,users.getPhoneNumber());
        return baseMapper.selectOne(qw);
    }

    @Override
    public Boolean updateLastLoginTime(Users users) {
        return super.updateById(users);
    }
    // 读代码  把下面代码看懂
    @Override
    public UserRolesAndPermissions selectRoAndPeByUserId(Long userId) {
        //认证所需的角色和权限
        UserRolesAndPermissions urap = new UserRolesAndPermissions();
        //通过用户id获取所有的角色
        LambdaQueryWrapper<UsersAndRoles> qw = new LambdaQueryWrapper<>();
        qw.eq(UsersAndRoles::getUserId,userId);
        List<UsersAndRoles> usersAndRoles = uarm.selectList(qw);
        //角色列表查询角色
        List<Long> roleIds = usersAndRoles.stream().map(o -> o.getRoleId()).collect(Collectors.toList());
        if(roleIds.size() > 0){
            Set<String> roles = rm.selectBatchIds(roleIds).stream().map(o -> o.getName()).collect(Collectors.toSet());
            //角色合集
            urap.setRoles(roles);
            //通过角色id查询所有的权限(角色和权限的中间表)
            QueryWrapper<RolesAndPermissions> rolesqw = new QueryWrapper<>();
            rolesqw.in(true,"role_id",roleIds);
            Set<Long> permissionsIds = rapm.selectList(rolesqw).stream().map(o -> o.getPermissionId()).collect(Collectors.toSet());
            if(permissionsIds.size() > 0){
                //通过权限id查询具体有哪些权限
                Set<String> permissions = pm.selectBatchIds(permissionsIds).stream().map(o -> o.getPerms()).collect(Collectors.toSet());
                urap.setPermissions(permissions);
            }
        }
        return urap;
    }
}
